package org.hank.wanandroid.ui

import android.content.Intent
import android.os.Bundle
import com.tencent.mmkv.MMKV
import kotlinx.android.synthetic.main.activity_setting.*
import org.greenrobot.eventbus.EventBus
import org.hank.commom.base.BaseActivity
import org.hank.commom.utils.CacheDataManager
import org.hank.wanandroid.R
import org.hank.wanandroid.bean.LogoutEvent
import org.hank.wanandroid.constants.Constants
import org.hank.wanandroid.utils.showSnackToast
import org.hank.wanandroid.utils.showTipsDialog
import org.hank.wanandroid.viewmodel.SettingViewModel

class SettingActivity : BaseActivity() {
    override val layoutResId: Int
        get() = R.layout.activity_setting

    private val settingViewModel by getViewModel(SettingViewModel::class.java) {
        logOutRet.observe(it) {
            setting_logout.isEnabled = true
            MMKV.defaultMMKV()?.removeValueForKey(Constants.LOGIN_INFO)
            MMKV.defaultMMKV()?.putBoolean(Constants.LOGIN_STATUS, false)
            EventBus.getDefault().post(LogoutEvent())
            showSnackToast("退出登录成功")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setting_logout.setOnClickListener {
            if (MMKV.defaultMMKV()!!.getBoolean(Constants.LOGIN_STATUS, false)) {
                showTipsDialog(this, "是否退出登录?") {
                    setting_logout.isEnabled = false
                    settingViewModel.logout()
                }
            } else
                showSnackToast("当前暂未登陆")
        }
        //获取缓存区大小
        text_setting_cache.text = CacheDataManager.getTotalCacheSize(this)
        setting_clear_cache.setOnClickListener {
            showTipsDialog(this, "是否清除缓存?") {
                CacheDataManager.clearAllCache(this)
                showSnackToast("缓存清除成功")
                text_setting_cache.text = CacheDataManager.getTotalCacheSize(this)
            }
        }
        text_setting_version.text = packageManager.getPackageInfo(this.packageName, 0).versionName
        setting_project_url.setOnClickListener {
            var intent = Intent(this, WebActivity::class.java)
            var bundle = Bundle()
            var link = resources.getString(R.string.project_link)
            bundle.putString(Constants.WEB_URL, link)
            bundle.putString(Constants.WEB_TITLE, "作者项目地址")
            intent.putExtras(bundle)
            startActivity(intent)
        }
        setting_version_notice.setOnClickListener {
            showTipsDialog(this, "本项目仅供学习使用，所有接口和API均来自 www.wanandroid.com")
        }
    }

    override fun showToast(msg: String) {
        super.showToast(msg)
        setting_logout.isEnabled = true
    }
}